package com.kchouse.homepage;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.kchouse.Alipay.PayResult;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.earnestDetail;
import com.kchouse.bean.quoteDetail;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.BaseApp;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.ArrayList;
import java.util.Map;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static com.kchouse.Alipay.Alipayapi.SDK_PAY_FLAG;

public class DepositDetailsActivity extends BaseActivity implements View.OnClickListener{

    private DepositDetailsActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_ok;
    private TextView tv_userMobile;
    private TextView tv_carNumber;
    private TextView tv_totalHours;
    private TextView tv_totalParts;
    private TextView tv_quoteTime;
    private TextView tv_totalAll;
    private TextView tv_dealAll;
    private Intent intent;
    private String id;
    private Double totalHours;
    private Double totalParts;
    private ArrayList<earnestDetail> list = new ArrayList<>();
    private ArrayList<earnestDetail> list1 = new ArrayList<>();
    private ArrayList<earnestDetail> list2 = new ArrayList<>();
    private ListView lv_item1;
    private ListView lv_item2;
    private LvAdapter adapter1;
    private LvAdapter2 adapter2;
    public static String orderNo;
    private String earnestId;
    boolean isweixin = true;//默认微信支付

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit_details);

        mContent = this;
        intiData();
        intiView();
    }


    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("定金详情");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_ok = (TextView) findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(this);


        tv_userMobile = (TextView) findViewById(R.id.tv_userMobile);
        tv_carNumber = (TextView) findViewById(R.id.tv_carNumber);
        tv_totalHours = (TextView) findViewById(R.id.tv_totalHours);
        tv_totalParts = (TextView) findViewById(R.id.tv_totalParts);
        tv_quoteTime = (TextView) findViewById(R.id.tv_quoteTime);
        tv_totalAll = (TextView) findViewById(R.id.tv_totalAll);
        tv_dealAll = (TextView) findViewById(R.id.tv_dealAll);

        lv_item1 = (ListView) findViewById(R.id.lv_item1);
        lv_item2 = (ListView) findViewById(R.id.lv_item2);
        adapter1 = new LvAdapter();
        lv_item1.setAdapter(adapter1);
        adapter2 = new LvAdapter2();
        lv_item2.setAdapter(adapter2);

    }

    private void intiData() {
        intent = getIntent();
        id = intent.getStringExtra("id");
//        GetDepositdetails(id);
    }



    /**
     * 获取定金详情
     * @param id
     */
    private void GetDepositdetails(String id) {
        String url = API.GetDepositdetails + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("id", id);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    JSONObject datajson = JSONObject.parseObject(json.getString("data"));
                    JSONObject earnestjson = JSONObject.parseObject(datajson.getString("earnest"));

                    earnestId=   earnestjson.getString("earnestId");
                    String status = earnestjson.getString("status");
                    if(status.equals("NO")){

                        tv_ok.setVisibility(View.VISIBLE);
                    }else {
                        tv_ok.setVisibility(View.GONE);
                    }
                    String userMobile = earnestjson.getString("userMobile");
                    tv_userMobile.setText("手机号：" + userMobile );
                    String carNumber = earnestjson.getString("carNumber");
                    tv_carNumber.setText("车牌号：" + carNumber);
                    totalHours = earnestjson.getDouble("totalHours");
                    tv_totalHours.setText("工时小计：" + totalHours + "元");
                    totalParts = earnestjson.getDouble("totalParts");
                    tv_totalParts.setText("配件小计：" + totalParts + "元");
                    String carTime = earnestjson.getString("carTime");
                    tv_quoteTime.setText("报价时间：" + carTime);
                    double toatlall = totalHours + totalParts;
                    tv_totalAll.setText("总计：" + toatlall + "元");
                    Double price = earnestjson.getDouble("price");
                    tv_dealAll.setText("定金：" + price + "元");

                    list.clear();
                    list1.clear();
                    list2.clear();
                    list.addAll(JSONObject.parseArray(earnestjson.getString("earnestDetailList"), earnestDetail.class));
                    for (int i = 0; i < list.size(); i++) {
                        earnestDetail item = list.get(i);
                        if (item.getType().equals("HOURS")) {
                            list1.add(item);
                        } else {
                            list2.add(item);
                        }
                    }
                    adapter1.notifyDataSetChanged();
                    adapter2.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_ok:
//                createOrder();
                Payshowdialog();
                break;
        }
    }

    public void Payshowdialog() {
         isweixin = true;
        final String items[] = {"微信支付", "支付宝支付"};
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setIcon(R.mipmap.icon)//设置标题的图片
                .setTitle("支付类型")//设置对话框的标题
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.getInstanc(mContent).showToast(items[which]);
                        if (items[which].equals("微信支付")) {
                            isweixin = true;
                        } else {
                            isweixin = false;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

//                        if (isweixin){
                        createOrder(isweixin);
//                        }else {
//                            //TODO 支付宝订单未新建
//                            alipay();
//                        }
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    /**
     * 创建订单
     */
    private void createOrder(final boolean isweixin) {
        String url = API.PostCreateOrder;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ob.put("suitId", earnestId);
        ob.put("userId", MainActivity.userid);
        ob.put("cashNum", "0");
        ob.put("suitCount", "1");
        ob.put("type", "EARNEST");
        params.applicationJson(ob);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    orderNo= data.getString("orderNo");

                    if (isweixin) {
                        weixin();
                    } else {
                        alipay();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if(data.getString("code").equals("401")||data.getString("code").equals("400"))
                    {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }

    /**
     * 支付宝支付
     */
    private void alipay() {
        String url = API.PostaliPay;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("outTradeNo", orderNo);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);

                    showalipay(data.getString("orderStr"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }

    //支付页面
    private void showalipay(String sign) {
//        boolean rsa2 = (Alipayapi.RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Alipayapi.APPID, rsa2);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? Alipayapi.RSA2_PRIVATE :Alipayapi.RSA_PRIVATE;
//        String sign2 = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);

//        final String orderInfo = orderNo + "&" +sign;
        final String orderInfo = sign;
//        final String orderInfo = orderParam + "&" +sign2;
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mContent);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //支付宝支付结果回调
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            Log.e("====",msg.toString());
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
//                        ToastUtils.getInstanc(mContent).showToast("支付成功");
                        ToastUtils.getInstanc(mContent).showToast("支付成功");
                        intent.putExtra("Order","3");//定金订单
                        intent.setClass(mContent, PayResultsActivity.class);
                        startActivity(intent);
                        DepositDetailsActivity.orderNo="";
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
//                        ToastUtils.getInstanc(mContent).showToast("支付失败");
//                        ToastUtils.getInstanc(mContent).showToast(payResult.toString());
                        Log.e("====",payResult.toString());
                        ToastUtils.getInstanc(mContent).showToast("支付失败");
                        PostCancelOrder();
                    }
                    break;
                }
            }
        }

        ;
    };

    /**
     * 取消订单
     */
    private void PostCancelOrder() {
        String url = API.PostCancelOrder + BuyPrestoreOrderActivity.orderNo;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("orderId", BuyPrestoreOrderActivity.orderNo);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }

        });
    }



    /**
     * 微信支付
     */
    private void weixin() {
        String url = API.PostCreateOrder2 + orderNo;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("suitId", suit.getString("id"));

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    payWeChat(data.getString("appid"), data.getString("partnerid"), data.getString("prepayid"), data.getString("noncestr"), data.getString("timestamp"), data.getString("sign"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if(data.getString("code").equals("401")||data.getString("code").equals("400"))
                    {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }


    /**
     * 发起微信支付
     */
    private void payWeChat(String WeChatID, String WeChatpartnerId, String prepayId, String nonceStr, String timeStamp, String sign) {

        if (!BaseApp.msgApi.isWXAppInstalled()) {
            ToastUtils.getInstanc(mContent).showToast("请先安装微信！");
            return;
        }
        PayReq payReq = new PayReq();
        payReq.appId = WeChatID;//应用ID
        payReq.partnerId = WeChatpartnerId;//商户号
        payReq.prepayId = prepayId;//预支付交易会话ID
        payReq.packageValue = "Sign=WXPay";//扩展字段
        payReq.nonceStr = nonceStr;//随机字符串
        payReq.timeStamp = timeStamp;//时间戳
//        payReq.extData= "app data"; // optional
        payReq.sign = sign;//签名
//        BaseApp.msgApi.sendReq(payReq);
        BaseApp.msgApi.sendReq(payReq);
    }

    @Override
    protected void onResume() {
        super.onResume();

        GetDepositdetails(id);

        BaseResp req = BaseApp.getResp();
        if (req != null) {
            BaseApp.setResp(null);
        }
    }




    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list1.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            earnestDetail item = list1.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");
            RelativeLayout rl_1 = (RelativeLayout) view.findViewById(R.id.rl_1);
            rl_1.setVisibility(View.GONE);
//            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
//            tv_item.setOnClickListener(new OfferDetailsActivity.Lv1OnClick(item, tv_item));
            return view;
        }
    }



    class LvAdapter2 extends BaseAdapter {
        @Override
        public int getCount() {
            return list2.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            earnestDetail item = list2.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");
            RelativeLayout rl_1 = (RelativeLayout) view.findViewById(R.id.rl_1);
            rl_1.setVisibility(View.GONE);
//            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
//            tv_item.setOnClickListener(new Lv2OnClick(item, tv_item));
            return view;
        }
    }
}
